package cevent.source.cloudcenter.business.controller.admin;/**
 * Created by Cevent on 2021/5/17.
 */

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author cevent
 * @description 验证码接口
 * @date 2021/5/17 18:15
 */
@RestController
@RequestMapping("/admin/kaptcha")
public class KaptchaController {
    public static final String BUSINESS_NAME="图形验证码";
    public static final Logger LOG= LoggerFactory.getLogger(KaptchaController.class);
    //@Qualifier：限定@Autowired自动注入的@bean
    @Qualifier("getDefaultKaptcha")
    @Autowired
    DefaultKaptcha defaultKaptcha;

    //注入redis
    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/image-code/{imgCodeToken}")
    public void getKaptcha(@PathVariable(value="imgCodeToken") String imgCodeToken,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        //客户端传入sessionId
        LOG.info("客户端传入sessionId：{}",request.getSession().getId());
        //指定字节数组输出流
        ByteArrayOutputStream jpegOutputStream=new ByteArrayOutputStream();
        try {
            //1.自动生成验证码字符串
            String createCode=defaultKaptcha.createText();
            //2.将生成的验证码放入会话缓存，后需验证码的时候方便调用
            request.getSession().setAttribute(imgCodeToken,createCode);

            //TODO 注入redis(key：传入的8位uuid，value：生成的kaptcha文本，过期时间：3000，时间单位：TimeUnit)
            //超过过期时间，redis将清空存入的数据,300s，5分钟后清空数据，存储为key
            /**1.不启用redis*/
            redisTemplate.opsForValue().set(imgCodeToken,createCode,300, TimeUnit.SECONDS);
            String redisCode=(String)redisTemplate.opsForValue().get(imgCodeToken);
            LOG.info("redis存储的code：{}",redisCode);
            //3.将验证码字符串放入jpeg
            BufferedImage challengeKaptcha=defaultKaptcha.createImage(createCode);
            ImageIO.write(challengeKaptcha,"jpg",jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            e.printStackTrace();
            return ;
        }

        //定义response输出类型为image/jpeg(需要转换字节数组)，使用response输出流，输出图片的byte数组
        byte[] jpgChallengeKaptcha=jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control","no-store");
        response.setHeader("Pragma","no-cache");
        //设置过期时间
        response.setDateHeader("Expires",0);
        //设置图片格式，注意，图片jpg格式，对应的contentType=image/jpeg
        response.setContentType("image/jpeg");
        //配置response中的输出流
        ServletOutputStream outputStream=response.getOutputStream();
        //输出流写入内容
        outputStream.write(jpgChallengeKaptcha);
        LOG.info("图片验证码输出：");
        outputStream.flush();
        outputStream.close();
    }
}
